package manager

import db.Wares
import db.WaresCargo
import event.InventoryChangedEvent
import mvc.model.inventory.GoodsTypeWare
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import task.RefreshWaresCargoTask

object WaresManager {

    var SelectIndex = 0
    var InventoryWaresCargo = ArrayList<WaresCargo>()
        private set

    fun toJson(): JSONArray {
        val arr = JSONArray()
        for (wc in InventoryWaresCargo) {
            arr.put(wc.toJson())
        }
        return arr
    }

    fun findByWaresId(waresId: String): WaresCargo {
        for (wc in InventoryWaresCargo) {
            if (wc.wares.id == waresId) {
                return wc
            }
        }
        throw IllegalArgumentException("没有找到对应的商品:$waresId")
    }

    fun setIndexByWaresId(waresId: String) {
        var index = 0
        for (wc in InventoryWaresCargo) {
            if (wc.wares.id == waresId) {
                SelectIndex = index
                return
            }
            index ++
        }

        throw IllegalArgumentException("没有找到对应的商品:$waresId")
    }

    fun selectInfo() = InventoryWaresCargo[SelectIndex]

    fun toGoodsTypes(): ArrayList<GoodsTypeWare> {
        val list = ArrayList<GoodsTypeWare>()
        InventoryWaresCargo.forEach { info ->
            info.cargos.forEach { goodsType ->
                list.add(GoodsTypeWare(goodsType, info.wares.name, info.wares.price.toString()))
            }
        }
        return list
    }

    // 如果售罄 将不显示
    private fun updateIfNotEmpty(waresList: ArrayList<Wares>) {
        val wareCargos = ArrayList<WaresCargo>()
        for (wares in waresList) {
            val waresCargo = WaresCargo.withWares(wares)
            if (0 == waresCargo.size()) {
                continue
            }
            wareCargos.add(waresCargo)
        }
        AppTask.post {
            InventoryWaresCargo = wareCargos
            EventBus.getDefault().post(InventoryChangedEvent())
        }
    }

    fun reloadWithDatabase() {
        val waresList = Wares.withDatabase()
        updateIfNotEmpty(waresList)
    }

    fun reloadWithDatabseOrServer() {
        val waresList = Wares.withDatabase()
        if (waresList.isNotEmpty()) { // 商品表不为空, 不是第一次安装
            updateIfNotEmpty(waresList)
            return
        }
        AsyncTask.post(RefreshWaresCargoTask())
    }

}

